<template>
    <div>
        <div id="mychart" ref="chartContainer" :style="{ width: '100%', height: height }"></div>
    </div>
</template>

<script>
export default {
    name: 'chart',
    props: {
        chartData: {
            type: Object,
            default: () => ({})
        },
        field: {
            type: String,
            default: ''
        },
        height:{
            type:String,
            default:'320px'
        },
        watchTime:{
            type: String,
            default: ''
        }
    },
    data() {
        return {
            myChart: null,
            resizeObserver: null 
        }
    },
    mounted() {
       
    },    
    activated() {
        if (this.myChart) {
            this.myChart.resize();
        }
    },
    deactivated() {
        if (this.myChart) {
            this.myChart.clear();
        }
    },
    beforeDestroy() {
        this.cleanupChart();
    },
    watch: {
        chartData: {
            handler(newVal, oldVal) {
                if (!this.isDataEqual(newVal, oldVal)) {
                    this.$nextTick(() => {
                        this.drawChart();
                    });
                }
            },
            deep: true
        },
    },
    methods: {
        isDataEqual(newVal, oldVal) {
            if (newVal === oldVal) return true;
            if (!newVal || !oldVal) return false;
            
            return newVal.point === oldVal.point && 
                JSON.stringify(newVal.valueData) === JSON.stringify(oldVal.valueData);
        },
        drawChart() {
            if (!this.$echarts) {
                return;
            }
            
            if (this.myChart) {
                this.updateChart(); 
                return;
            }
            
            const dom = this.$refs.chartContainer;
            if (!dom) return;
            
            try {
                this.myChart = this.$echarts.init(dom, null, { locale: "ZH" });
                this.myChart.setOption(this.getChartOption(), true);
                
                this.setupResizeObserver();
                
            } catch (error) {
                console.error('ECharts initialization failed:', error);
                this.cleanupChart();
            }
        },
        
        setupResizeObserver() {
            if (this.resizeObserver) {
                this.resizeObserver.disconnect();
                this.resizeObserver = null;
            }
            const dom = this.$refs.chartContainer;
            if (!dom || !this.myChart) return;

            this.resizeObserver = new ResizeObserver(() => {
                if (this.myChart) {
                    this.myChart.resize();
                }
            });
            
            this.resizeObserver.observe(dom);
        },
        
        getChartOption() {
            const {valueData, point, unit, valueMax, valueMin, valueLen} = this.chartData || {};
            let markData = [];
            let LineKeys = [];
            
            if (valueData && Array.isArray(valueData)) {
                valueData.forEach((item) => {
                    if (item && item.watchTime && item.value !== undefined) {
                        LineKeys.push([item.watchTime, Number(item.value)]);
                        
                        if (this.watchTime && this.field && 
                            item.watchTime == this.watchTime && 
                            item.value == this.field) {
                            markData = [item.watchTime, item.value];
                        }
                    }
                });
            }
            
            return {
                tooltip: {
                    trigger: 'axis',
                },
                title: {
                    left: 'center',
                    text: point || '',
                    textStyle: {
                        fontSize: 15, 
                        color: '#333', 
                        fontWeight: 'bold' 
                    }
                },
                grid: {
                    top: '15%',
                    left: '4%',
                    right: '4%',
                    bottom: '0%',
                    containLabel: true,
                    borderWidth: 1,
                    show: true,
                    borderColor: '#000',
                },
                toolbox: {
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'time',
                    axisLabel: {
                        formatter: (value) => {
                            return this.$echarts.format.formatTime('yyyy-MM-dd', value);
                        }
                    },
                    data: LineKeys,
                    show: true,
                    axisLine: {
                        show: true,
                        onZero: false, 
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            type: 'dashed',
                            color: '#a8a8a8',
                        },
                    },
                },
                yAxis: {
                    type: 'value',
                    name: `单位(${unit || ''})`,
                    axisLabel: {
                        formatter: function(value) {
                            return value.toString();
                        }
                    },
                    interval: Number(valueLen) || undefined, 
                    max: Number(valueMax) || undefined,
                    min: Number(valueMin) || undefined,
                    axisLine: {
                        show: true,
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {     
                            type: 'dashed',
                            color: '#a8a8a8',
                        },
                    },
                },
                dataZoom: [
                    {
                        type: 'inside',
                    },
                ],
                series: [
                    {
                        name: point || '',
                        type: 'line',
                        symbol: 'none',
                        areaStyle: {
                            origin: 'start', 
                            color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: 'rgba(58, 77, 233,1)' },
                                { offset: 0.5, color: 'rgba(58, 77, 233, 0.2)' },
                                { offset: 1, color: 'rgba(58, 77, 233, 0)' }
                            ])
                        },
                        data: LineKeys, 
                        markPoint: {
                            data: markData.length ? [{
                                coord: markData,
                                label: {
                                    show: true,
                                    formatter: function(params) {
                                        return params.data.coord[1];
                                    },
                                },
                                itemStyle: {
                                    color: 'rgb(255, 0, 0)'
                                },
                            }] : []
                        }
                    },
                ]
            };
        },
        
        updateChart() {
            if (!this.myChart) return;
            try {
                this.myChart.setOption(this.getChartOption(), true);
            } catch (error) {
                console.error('Chart update failed:', error);
            }
        },
        cleanupChart() {
            if (this.resizeObserver) {
                this.resizeObserver.disconnect();
                this.resizeObserver = null;
            }
            if (this.myChart) {
                try {
                    this.myChart.dispose();
                } catch (error) {
                    console.error('Chart disposal failed:', error);
                } finally {
                    this.myChart = null;
                }
            }
        },
        clearChart() {
            if (this.myChart) {
                this.myChart.clear();
            }
        },
    },
}
</script>

<style scoped>

</style>